package com.mengdie.shuidi.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.utils.EmptyUtils;
import com.blankj.utilcode.utils.LogUtils;
import com.blankj.utilcode.utils.ScreenUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.mengdie.shuidi.AppContext;
import com.mengdie.shuidi.OkHeader;
import com.mengdie.shuidi.R;
import com.mengdie.shuidi.event.RegisterEvent;
import com.mengdie.shuidi.helper.UIHelper;
import com.mengdie.shuidi.manager.MDAccountMgr;
import com.mengdie.shuidi.manager.MDUserMgr;
import com.mengdie.shuidi.model.BaseModel;
import com.mengdie.shuidi.model.ExceedUserEnetity;
import com.mengdie.shuidi.model.SessionEnetity;
import com.mengdie.shuidi.model.UserEnetity;
import com.mengdie.shuidi.utils.DeviceUuidFactory;
import com.mengdie.shuidi.utils.ToastUtil;
import com.mengdie.shuidi.utils.common.AppUtils;
import com.mengdie.shuidi.utils.common.MD5Util;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;


public class LoginActivity extends BaseActivity {
    @Bind(R.id.iv_login_name)
    ImageView mIvLoginName;
    @Bind(R.id.iv_login_pass)
    ImageView mIvLoginPass;
    @Bind(R.id.btn_login_submit)
    Button mBtnLoginSubmit;
    @Bind(R.id.et_login_name)
    EditText mEtLoginName;
    @Bind(R.id.rl_login_name)
    RelativeLayout mRlLoginName;
    @Bind(R.id.et_login_password)
    EditText mEtLoginPassword;
    @Bind(R.id.rl_login_password)
    RelativeLayout mRlLoginPassword;
    @Bind(R.id.tv_login_forget)
    TextView mTvLoginForget;
    @Bind(R.id.cb_login_pass)
    CheckBox mCbLoginPass;
    @Bind(R.id.btn_login_regist)
    Button mBtnLoginRegist;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        //   EventBus.getDefault().register(this);
        ButterKnife.bind(this);
        init();
    }

    public void init() {
        LogUtils.e("分辨率：" + ScreenUtils.getScreenHeight() + "   " + ScreenUtils.getScreenWidth());
        MDAccountMgr.getInstance().setLogin(false);
        if (MDAccountMgr.getInstance().isPassowrd()) {
            String name = MDAccountMgr.getInstance().getLoginName();
            String pass = MDAccountMgr.getInstance().getLoginPwd();
            if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(pass)) {
                mEtLoginName.setText(name);
                mEtLoginPassword.setText(pass);
            }
        }

        mEtLoginName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    mRlLoginName.setSelected(true);
                    mRlLoginPassword.setSelected(false);
                } else {
                    mRlLoginName.setSelected(false);
                }
            }
        });

        mEtLoginPassword.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    mRlLoginPassword.setSelected(true);
                    mRlLoginName.setSelected(false);
                } else {
                    mRlLoginPassword.setSelected(false);
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //  EventBus.getDefault().unregister(this);
        //根据 Tag 取消请求
        OkGo.getInstance().cancelTag(this);
    }

    @OnClick({R.id.btn_login_submit, R.id.tv_login_forget, R.id.btn_login_regist})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_login_submit:
                String name = mEtLoginName.getText().toString();
                String password = mEtLoginPassword.getText().toString();
                if (EmptyUtils.isNotEmpty(name)) {
                    if (EmptyUtils.isNotEmpty(password)) {
                        login(name, password);
                    } else {
                        ToastUtil.showToast(getResources().getString(R.string.et_is_password_empty));
                    }
                } else {
                    ToastUtil.showToast(getResources().getString(R.string.et_is_name_empty));
                }
                break;
            case R.id.tv_login_forget:
                Intent forget = new Intent(LoginActivity.this, ForGetActivity.class);
                startActivity(forget);
                break;
            case R.id.btn_login_regist:
                Intent regist = new Intent(LoginActivity.this, RegistActivity.class);
                startActivity(regist);
                break;
        }
    }

    /**
     * 接收注册页面传递火来的消息
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessage(RegisterEvent event) {
        mCbLoginPass.setChecked(event.getIsChecked());
        mEtLoginName.setText(event.getUseName());
        mEtLoginPassword.setText(event.getPassWord());
    }

    /**
     * 登录
     *
     * @param name
     * @param password
     */
    public void login(final String name, final String password) {

        AppUtils.AppInfo appInfo = AppUtils.getAppInfo(this);
        int versionCode = 1;
        if (appInfo != null) {
            versionCode = appInfo.getVersionCode();
        }


        HashMap<String, String> map = new HashMap<>();
        map.put("username", name);
        map.put("password", password);
        map.put("device_token", MDAccountMgr.getInstance().getDeviceToken());
        map.put("client_id", MD5Util.md5(new DeviceUuidFactory(AppContext.getInstance()).getDeviceUuid().toString()));
        JSONObject jsonObject = new JSONObject(map);

        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHead(this)).post(AppContext.getInstance().getBaseUrl() + "account/login_new")
                .tag(this)
                .upJson(jsonObject.toString())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        BaseModel baseModels = gson.fromJson(s, BaseModel.class);
                        if (baseModels.getRet().equals("0")) {
                            Type userType = new TypeToken<BaseModel<SessionEnetity>>() {
                            }.getType();
                            BaseModel<SessionEnetity> baseModel;
                            try {
                                baseModel = gson.fromJson(s, userType);
                            } catch (JsonSyntaxException e) {
                                baseModel = gson.fromJson(s, BaseModel.class);
                            }
                            SessionEnetity sessionInfo = baseModel.getData();
                            MDAccountMgr.getInstance().setSessionId(sessionInfo.getSession());
                            UserEnetity user = sessionInfo.getUserInfo();
                            MDUserMgr.getInstance().setAvatar(user.getAvatar());
                            MDUserMgr.getInstance().setAwardFlag(user.getAward_flag());
                            MDUserMgr.getInstance().setId(user.getId());
                            MDUserMgr.getInstance().setUsername(user.getUsername());
                            MDUserMgr.getInstance().setShowUsername(user.getShowUsername());
                            MDUserMgr.getInstance().setNickname(user.getNick_name());
                            MDUserMgr.getInstance().setChange(user.getChange());
                            MDUserMgr.getInstance().setEmail(user.getEmail());
                            MDUserMgr.getInstance().setNum(user.getNum() + "");
                            MDUserMgr.getInstance().setPhone(user.getPhone());
                            MDUserMgr.getInstance().setMoney(Double.valueOf(user.getMoney()));
                            MDUserMgr.getInstance().setLastTime(user.getLast_time());
                            MDUserMgr.getInstance().setLastTimeType(user.getLast_time_type());
                            MDUserMgr.getInstance().setStatus(user.getStatus());
                            MDUserMgr.getInstance().setToken(user.getToken());
                            MDUserMgr.getInstance().setTime(user.getExpire_time_format());
                            MDUserMgr.getInstance().setCoupoum(user.getCoupoum());
                            MDUserMgr.getInstance().setLogin(true);//保存到类

                            MDUserMgr.getInstance().setThreeDayExpire(user.getThreeDayExpire());
                            MDAccountMgr.getInstance().setLogin(true);//保存到内存
                            MDAccountMgr.getInstance().setLoginName(user.getShowUsername());
                            MDAccountMgr.getInstance().setLoginPwd(password);
                            if (mCbLoginPass.isChecked()) {
                                MDAccountMgr.getInstance().setPassowrd(true);

                            } else {
                                MDAccountMgr.getInstance().setPassowrd(false);
                            }

                            MDAccountMgr.getInstance().writeToCache(LoginActivity.this);

                            Intent login = new Intent(LoginActivity.this, MainActivity.class);
                            startActivity(login);
                            finish();
                        } else if (baseModels.getRet().equals("1")) {
                            Type exceed = new TypeToken<BaseModel<List<ExceedUserEnetity>>>() {
                            }.getType();
                            BaseModel<List<ExceedUserEnetity>> exceeModel;
                            try {
                                exceeModel = gson.fromJson(s, exceed);
                            } catch (JsonSyntaxException e) {
                                exceeModel = gson.fromJson(s, BaseModel.class);
                            }
                            if (exceeModel.getCode().equals("overtop")) {
                                UIHelper.showTerminal(LoginActivity.this, exceeModel.getData(), UIHelper.LOGIN_DIALOG, "2");
                            } else {
                                ToastUtil.showToast(baseModels.getMsg());
                            }
                        } else {
                            ToastUtil.showToast(baseModels.getMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        ToastUtil.showToast("网络请求失败");

                    }

                });
    }


}
